#include "my_header.h"

int authPasswd(int sockfd) {
    char username[256];
    char password[256];
    train_t auth_train;

    printf("请输入用户名:\n");        
    if (fgets(username, sizeof(username), stdin) == NULL) {
        printf("用户名无效!\n");
        return -1;
    }
    size_t len = strlen(username);
    if (len > 0 && username[len - 1] == '\n') { //去除结尾的换行符
        username[len - 1] = '\0';
    }

    printf("请输入密码:\n");
    if (fgets(password, sizeof(password), stdin) == NULL) {
        printf("密码无效！\n");
        return -1;
    }
    len = strlen(password);
    if (len > 0 && password[len - 1] == '\n') {
        password[len - 1] = '\0';
    }

    bzero(&auth_train, sizeof(auth_train));
    auth_train.type = AUTH; 
    auth_train.lenth = strlen(username);
    strcpy(auth_train.value, username);
    send(sockfd, &auth_train, sizeof(auth_train.type) + sizeof(auth_train.lenth) + auth_train.lenth, MSG_NOSIGNAL);

    bzero(&auth_train, sizeof(auth_train));
    auth_train.type = AUTH; 
    auth_train.lenth = strlen(password);
    strcpy(auth_train.value, password);
    send(sockfd, &auth_train, sizeof(auth_train.type) + sizeof(auth_train.lenth) + auth_train.lenth, MSG_NOSIGNAL);

    char response[1024];   //接收服务端验证后的信息
    bzero(response, sizeof(response));
    int ret = recv(sockfd, response, sizeof(response) - 1, 0);
    //printf("ret = %d\n",ret);
    if (ret <= 0) {
        printf("验证失败: 服务端已断开\n");
        return -1;
    }

    response[ret] = '\0';
    //printf("response = %s\n",response);
    if (strcmp(response, "AUTH_SUCCESS") == 0) {
        printf("验证成功!\n");
        return 0;
    } else {
        printf("验证失败: %s\n", response);
        return -1;
    }
}
